package com.lineage.server.timecontroller.pet;

import com.lineage.server.model.Instance.L1DollInstance;
import com.lineage.server.serverpackets.S_DoActionGFX;
import com.lineage.server.serverpackets.ServerBasePacket;
import com.lineage.server.thread.GeneralThreadPool;
import com.lineage.server.world.WorldDoll;
import java.util.Collection;
import java.util.Iterator;
import java.util.Random;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class DollTimer extends TimerTask {
  private static final Log _log = LogFactory.getLog(DollTimer.class);
  
  private static Random _random = new Random();
  
  private ScheduledFuture<?> _timer;
  
  public void start() {
    int timeMillis = 30000;
    this._timer = GeneralThreadPool.get().scheduleAtFixedRate(this, 30000L, 30000L);
  }
  
  public void run() {
    try {
      Collection<L1DollInstance> allDoll = WorldDoll.get().all();
      if (allDoll.isEmpty())
        return; 
      Iterator<?> iter = allDoll.iterator();
      while (iter.hasNext()) {
        L1DollInstance doll = (L1DollInstance)iter.next();
        int time = doll.get_time() - 30;
        if (time <= 0) {
          outDoll(doll);
        } else {
          doll.set_time(time);
          if (doll.isDead())
            continue; 
          checkAction(doll);
        } 
        Thread.sleep(50L);
      } 
    } catch (Exception e) {
      _log.error("魔法娃娃处理时间轴异常重启", e);
      GeneralThreadPool.get().cancel(this._timer, false);
      DollTimer dollTimer = new DollTimer();
      dollTimer.start();
    } 
  }
  
  private static void outDoll(L1DollInstance doll) {
    try {
      if (doll != null) {
        if (doll.destroyed())
          return; 
        doll.deleteDoll();
      } 
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
  }
  
  private void checkAction(L1DollInstance doll) {
    try {
      if (doll.getX() == doll.get_olX() && doll.getY() == doll.get_olY()) {
        int actionCode;
        if (_random.nextBoolean()) {
          actionCode = 66;
        } else {
          actionCode = 67;
        } 
        doll.broadcastPacketAll((ServerBasePacket)new S_DoActionGFX(doll.getId(), actionCode));
      } 
      doll.set_olX(doll.getX());
      doll.set_olY(doll.getY());
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
  }
}
